from django import template
from django.db.models import Count
from django.db.models.functions import TruncMonth

from blog import models
from blog.models import UserInfo

register = template.Library()



@register.inclusion_tag("classfication.html")
def get_classification_style(username):
    user = UserInfo.objects.filter(username=username).first()
    # 查询当前站点对象
    blog = user.blog

    # 查询当前站点的所有分类和对应的文章数
    cate_list = models.Category.objects.filter(blog=blog).values("pk").annotate(c=Count("article__title")).values_list(
        "title", "c")

    # 查询当前站点的每个标签和对应的文章数
    tag_list = models.Tag.objects.filter(blog=blog).values("pk").annotate(c=Count("article")).values_list("title", "c")

    # 查询当前站点每个年月和对应的文章数
    date_list = models.Article.objects.filter(user=user).annotate(month=TruncMonth('create_time')).values(
        'month').annotate(c=Count('nid')).values_list('month', 'c')

    return {'cate_list': cate_list, 'tag_list': tag_list, 'date_list': date_list, 'blog': blog, "username": username}

